package com.jcark.ui.utils

import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
import android.text.InputType
import android.view.Window
import android.view.WindowManager
import android.widget.EditText
import java.lang.Exception
import java.lang.reflect.Method

/**
 * Description: <br>
 * @author King.Zi<br>
 * @date 2022/8/23<br>
 * Email: 78688689@qq.com
 */
object UIUtils {
    fun isNetworkAvailable(context: Context): Boolean {
        val manager = context.applicationContext.getSystemService(
            Context.CONNECTIVITY_SERVICE
        ) as ConnectivityManager
        val info = manager.activeNetworkInfo
        return null != info && info.isAvailable
    }

    /**
     * 隐藏系统键盘 (用这个方法关闭系统键盘就不会出现光标消失的问题了)
     *
     * @param window
     * @param editText
     */
    fun hideSoftInputMethod(window: Window, editText: EditText) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        var methodName: String? = null
        val currentVersion = Build.VERSION.SDK_INT
        if (currentVersion >= Build.VERSION_CODES.JELLY_BEAN) {
            // 4.2
            methodName = "setShowSoftInputOnFocus"
        } else if (currentVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            // 4.0
            methodName = "setSoftInputShownOnFocus"
        }
        if (methodName == null) {
            //最低级最不济的方式，这个方式会把光标给屏蔽
            editText.inputType = InputType.TYPE_NULL
        } else {
            val cls = EditText::class.java
            val setShowSoftInputOnFocus: Method
            try {
                setShowSoftInputOnFocus = cls.getMethod(methodName, Boolean::class.javaPrimitiveType)
                setShowSoftInputOnFocus.isAccessible = true
                setShowSoftInputOnFocus.invoke(editText, false)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}